from utils import device,format
from lib.net.index import wlan
import json

device_id = device.get_id()
platform = device.get_platform()

user_agent = f"id/{device_id} platform/{platform}"


def GET(request_url, params=None, type="raw"):
    """AT TCP GET请求"""
    if params is None:
        params = {}
    parsed = format.format_url(request_url)
    domain = parsed["domain"]
    port = parsed["port"]
    path = parsed["path"]
    cmd = f"GET /{path} HTTP/1.1\r\nHost: {domain}\r\nUser-Agent: {user_agent}\r\n\r\n"  # Connection: close\r\n\r\n
    wlan.connect_server(domain, port)
    return wlan.send_request(cmd, 2000)


def POST(request_url, payload=None, type="raw"):
    """AT TCP POST"""
    if payload is None:
        payload = {}
    parsed = format.format_url(request_url)
    domain = parsed["domain"]
    port = parsed["port"]
    path = parsed["path"]
    body = json.dumps(payload)
    length = len(body.encode("utf-8"))
    cmd = (
        f"POST /{path} HTTP/1.1\r\nHost: "
        + domain
        + f"\r\nUser-Agent: {user_agent}\r\n"
        + "Content-Type: application/json\r\n"
        + f"Content-Length: {length}\r\n\r\n"
        + f"{body}"
    )
    wlan.connect_server(domain, port)
    return wlan.send_request(cmd, 2000)

if __name__ == "__main__":
    from utils import device

    payload = {
        "op": "upload",
        "name": "dataset",
        "topic": "Tiot_bba1471x",
        "data": "at,1,2,3",
        "device_id": device.get_id(),
        "value": { "mcu": "rp2040", "type": "at" },
        "extra": {
            "device_info": device.get_info(),
        },
    }
    res = POST("http://www.hanxiaoxin.cn:8081/iot/upload", payload)
